package com.link.play.fit.ai.ui.main.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityOptionsCompat
import androidx.lifecycle.lifecycleScope
import com.google.firebase.firestore.Filter
import com.google.firebase.firestore.ListenerRegistration
import com.link.play.fit.ai.GlobalConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseFragment
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.viewBind
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.FgSettingsBinding
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.kv.AuthCache.isBurnedSwitch
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.ui.adjust.AdjustGoalsActivity
import com.link.play.fit.ai.ui.dialog.DeleteUserDialog
import com.link.play.fit.ai.ui.guide.ac.GuideAc
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.MainViewModel
import com.link.play.fit.ai.ui.setting.FeedbackAc
import com.link.play.fit.ai.ui.setting.PersonalDetailAc
import com.link.play.fit.ai.utils.DateEx.calculateAge
import com.link.play.fit.ai.utils.DateEx.getTimestampFromDateTime
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *Create by SleepDog on 2025-03-24
 */
class SettingsFg : BaseFragment<FgSettingsBinding>(FgSettingsBinding::inflate) {

    /**
     * 用来保存firestore的数据监听，在不需要的时候需要去除掉，这里固定写死了2个
     */
    private val observerList = ArrayList<ListenerRegistration>(2)

    /**
     * 用来防止多次请求刷新，因为有些数据改变的监听是有重合的
     */
    private var isUpdateData = false

    private val viewModel: MainViewModel by lazy {
        (requireActivity() as MainAc).viewModel
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.flPersonal.setOnClickListener {
            goToAc(
                PersonalDetailAc::class.java, ActivityOptionsCompat.makeSceneTransitionAnimation(
                    requireActivity(),
                    binding.tvPersonalTitle, getString(R.string.personal_details)
                ).toBundle()
            )
        }
        binding.flAdjustGoal.setThrottleListener {
            goToAc(AdjustGoalsActivity::class.java) {
                putExtra("data", viewModel.getCalendarData())
            }
        }
        binding.burnedSwitch.isChecked = isBurnedSwitch
        binding.burnedSwitch.setOnCheckedChangeListener { _, b ->
            isBurnedSwitch = b
        }

        binding.flAbout.setThrottleListener {
            val url = Uri.parse(GlobalConfig.URL_USE)
            startActivity(Intent(Intent.ACTION_VIEW, url))
        }
        binding.flPrivacy.setThrottleListener {
            val url = Uri.parse(GlobalConfig.URL_PRIVACY)
            startActivity(Intent(Intent.ACTION_VIEW, url))
        }
        binding.flDelete.setThrottleListener {
            val del = DeleteUserDialog {
                CloudStore.deleteAccount()
                goToAc(GuideAc::class.java) {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                }
            }.apply { build(requireActivity()) }
            del.show()
        }
        binding.flFeedback.setOnClickListener {
            goToAc(FeedbackAc::class.java)
        }

    }

    override fun lazyInit() {
        lifecycleScope.launch {
            //公英制状态变化
            GlobalConfig.imperialMetricFlow.collectLatest {
                updateWeightGoal(it)
            }
        }
        //监听用户信息变化
        observerList.add(
            CloudStore.observe(
                DOC_USER_GUIDE
            ) { value, error ->
//                if (error != null || isUpdateData) return@observe
                lifecycleScope.launch(Dispatchers.Default) {
                    val data =
                        if (value?.exists() == true) value.toObject(UserGuide::class.java) else null
                    val age = if (data != null) calculateAge(
                        getTimestampFromDateTime(
                            data.bornYear, data.bornMonth,
                            data.bornDay, 1, 1
                        )
                    ).toString() else "0"
                    val height =
                        if (GlobalConfig.imperialMetric) "${data?.heightCm} cm" else "${data?.heightFt} ft ${data?.heightIn} In"
                    withContext(Dispatchers.Main) {
                        viewBind {
                            tvAge.text = age
                            tvHeight.text = height
                        }
                    }
                }
            })
        //监听当天体重记录变化
        observerList.add(
            CloudStore.observeList(
                DOC_LOG_WEIGHT, DOC_LOG_WEIGHT
            ) { value, error ->
                if (error != null || isUpdateData) {
                    return@observeList
                }
                lifecycleScope.launch(Dispatchers.Default) {
                    val data =
                        if (value != null && !value.isEmpty) value.toObjects(LogWeightBean::class.java)
                            .last() else null
                    val currentWeight: String = if (GlobalConfig.imperialMetric) {
                        "${data?.weightKg} kg"
                    } else {
                        "${data?.weightLbs} lbs"
                    }
                    withContext(Dispatchers.Main) {
                        viewBind {
                            tvWeight.text = currentWeight
                        }
                    }
                }
            })
    }

    private fun updateWeightGoal(isMetric: Boolean) {
        isUpdateData = true
        lifecycleScope.launch(Dispatchers.Default) {
            val data = CloudStore.get<UserGuide>(DOC_USER_GUIDE)

            val age = if (data != null) calculateAge(
                getTimestampFromDateTime(
                    data.bornYear, data.bornMonth,
                    data.bornDay, 1, 1
                )
            ).toString() else "0"
            val height =
                if (GlobalConfig.imperialMetric) "${data?.heightCm} cm" else "${data?.heightFt} ft ${data?.heightIn} In"

            val dataCurrent = CloudStore.getListItem<LogWeightBean>(
                DOC_LOG_WEIGHT,
                DOC_LOG_WEIGHT,
                Filter.lessThanOrEqualTo("createTime", System.currentTimeMillis())
            )
            val currentWeight: String = if (isMetric) {
                "${dataCurrent?.weightKg} kg"
            } else {
                "${dataCurrent?.weightLbs} lbs"
            }
            withContext(Dispatchers.Main) {
                viewBind {
                    tvAge.text = age
                    tvHeight.text = height
                    tvWeight.text = currentWeight
                    isUpdateData = false
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        observerList.forEach {
            it.remove()
        }
        observerList.clear()
    }
}